package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private CacheService cacheService;

    /**
     * 首页加载 此时传递进来的minBehotTime非常大,保证直接能够获取到最新文章
     * publish_time(数据库里面文章发布时间) < minBehotTime
     *
     * @param dto
     * @return
     */
    @Override
    public List<ApArticle> load(ArticleHomeDto dto) {
        return apArticleMapper.loadArticleList(dto, ArticleConstants.LOADTYPE_LOAD_MORE);
    }

    //先从redis中查询,查询不到再去数据库查询
    @Override
    public List<ApArticle> load2(ArticleHomeDto dto) {
        if (dto == null) {
            return null;
        }
        String tag = dto.getTag();//频道id

        String s = cacheService.get(com.heima.model.common.enums.ArticleConstants.HOT_ARTICLE_FIRST_PAGE + tag);
        if (StringUtils.isBlank(s)) {
            //如果redis中没查到,直接回数据库查
            return load(dto);

        }
        return JSON.parseArray(s, ApArticle.class);
    }

    /**
     * 加载更多,上拉, publish_time(数据库里面文章发布时间) < minBehotTime(当前展示页面的最旧文章的时间)
     *
     * @param dto
     * @return
     */
    @Override
    public List<ApArticle> loadMore(ArticleHomeDto dto) {
        return apArticleMapper.loadArticleList(dto, ArticleConstants.LOADTYPE_LOAD_MORE);
    }

    /**
     * 刷新最新文章 下拉 publish_time(数据库里面文章发布时间) > maxBehotTime(当前展示页面的最新文章时间)
     *
     * @param dto
     * @return
     */
    @Override
    public List<ApArticle> loadNew(ArticleHomeDto dto) {
        return apArticleMapper.loadArticleList(dto, ArticleConstants.LOADTYPE_LOAD_NEW);
    }

    //生成静态html页面,保存至minIO,得到地址后写入ap_article表里的static_url字段
    @Async
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void generate(Long articleId) {
        //1. 根据articleId查询到content(文章详情)
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(queryWrapper);
        if (apArticleContent == null) {
            log.warn("文章内容不存在");
            return;
        }

        String content = apArticleContent.getContent();
        List contentArray = JSON.parseArray(content);//数据类型转化
        HashMap<String, Object> map = new HashMap<>(1);
        map.put("content", contentArray);

        //2. 调用freemarker插件生成html文件  参数一:模板  参数二:数据源
        InputStream inputStream = freemarkerGenerator.generate("article.ftl", map);

        //3. 调用minIO实现文件上传,并且得到URL prefix:前缀, filename:文件名, inputStream:输入流, type:类型
        String url = minIoTemplate.uploadFile("", articleId + ".html", inputStream, "html");

        //4. 将文件地址URL写入ap_article表里的static_url字段
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle == null) {
            log.warn("文章不存在");
            return;
        }
        apArticle.setStaticUrl(url);
        apArticleMapper.updateById(apArticle);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto articleDto) {
        //0.入参判空
        if (articleDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //1.入参处理
        Long id = articleDto.getId();

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);

        String content = articleDto.getContent();//文章的具体内容(新传入)
        if (StringUtils.isBlank(content)) {
            log.warn("文章内容为空");
            throw new RuntimeException("文章内容为空");
        }
        // 2.判断是新增还是修改
        if (id == null) {
            // 3.执行新增
            // 3.1 插入article表
            int apArticleResponse = apArticleMapper.insert(apArticle);
            if (apArticleResponse < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            //3.2 文章内容表新增
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(content);
            int apArticleContentResponse = apArticleContentMapper.insert(apArticleContent);
            if (apArticleContentResponse < 1) {
                log.warn("文章内容插入失败");
                throw new RuntimeException("文章内容插入失败");
            }

            //生成静态html页面,保存至minIO,得到地址后写入ap_article表里的static_url字段
            generate(apArticle.getId());

            //3.3 文章配置表新增
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsDelete(false);
            apArticleConfig.setIsDown(false);
            int apArticleConfigResponse = apArticleConfigMapper.insert(apArticleConfig);
            if (apArticleConfigResponse < 1) {
                log.warn("文章配置插入失败");
                throw new RuntimeException("文章配置插入失败");
            }
        } else {
            //3.执行修改

            // 3.1 修改article表
            int apArticleResponse = apArticleMapper.updateById(apArticle);
            if (apArticleResponse < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            // 3.2 修改内容表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(content);
            LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApArticleContent::getArticleId, id);
            int apArticleContentResponse = apArticleContentMapper.update(apArticleContent, queryWrapper);
            if (apArticleContentResponse < 1) {
                log.warn("文章内容修改失败");
                throw new RuntimeException("文章内容修改失败");
            }

            //生成静态html页面,保存至minIO,得到地址后写入ap_article表里的static_url字段
            generate(apArticle.getId());

        }
        return ResponseResult.okResult(apArticle.getId());
    }
}

